﻿Imports LSW.Data

Public Class ComboBoxEx
    Inherits ComboBox

    Sub New()
        MyBase.New()
        Me.DisplayMember = "Name"
        Me.ValueMember = "ID"
    End Sub

    Private m_tablename As String
    Public Property TableName() As String
        Get
            Return m_tablename
        End Get
        Set(ByVal value As String)
            m_tablename = value
        End Set
    End Property

    Private m_where As String = String.Empty
    Public Property Where() As String
        Get
            If m_where.IndexOf("and ") = 0 Then
                Return Mid(m_where, 5)
            Else
                Return m_where
            End If
        End Get
        Set(ByVal value As String)
            If Not String.IsNullOrEmpty(value) Then
                m_where = "and " & value
            Else
                m_where = value
            End If
        End Set
    End Property

    Public Property ConnectionString As String

    Private Sub ComboBoxEx_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If m_tablename = String.Empty Then Exit Sub
        If Me.Text.Trim = "" Then Exit Sub
        If e.KeyCode = Keys.Enter Then
            SetValue(Me.Text.Trim)
        End If
    End Sub

    Public Sub SetValue(ByVal v As String)
        If v = "" Then Exit Sub
        Dim dt As DataTable
        Dim sql As String
        If IsNumeric(v) Then
            sql = "SELECT [ID],[Name],[NameSpell] FROM {0} WHERE ID={1} {2}"
            sql = String.Format(sql, m_tablename, CInt(v), m_where)
        Else
            sql = "SELECT [ID],[Name],[NameSpell] FROM {0} WHERE ([Name] like '%{1}%' or [NameSpell] like '%{1}%') {2}"
            sql = String.Format(sql, m_tablename, v, m_where)
        End If
        dt = SqlHelper.ExecuteDataSet(ConnectionString, CommandType.Text, sql).Tables(0)
        Me.DataSource = dt
        If dt.Rows.Count > 0 Then
            Me.SelectedIndex = 0
        End If
    End Sub
End Class
